package com.wnn.demo.model.system.controller;


import com.github.pagehelper.PageInfo;
import com.wnn.demo.advice.MyException;
import com.wnn.demo.domain.User;
import com.wnn.demo.domain.UserLogin;
import com.wnn.demo.model.system.service.UserService;
import com.wnn.demo.pojo.Result;
import com.wnn.demo.pojo.ResultCode;
import com.wnn.demo.shiro.listener.ShiroSessionListener;
import com.wnn.demo.utils.BaseController;
import com.wnn.demo.utils.CaptchaUtil;
import com.wnn.demo.vo.MenuTreeVo;
import com.wnn.demo.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "/system", tags={"用户登录注册接口"})
@RestController
@RequestMapping("/system")
public class UserController extends BaseController {


    @Autowired
    private UserService userService;

    @Autowired
    private ShiroSessionListener shiroSessionListener;

    @Autowired
    private CaptchaUtil captchaUtil;

    public static final String KEY_CAPTCHA = "KEY_CAPTCHA";





    @PostMapping("/regpicture")
    public Result Regpicture(MultipartFile file) {
        //文件名
        String fileName = file.getOriginalFilename();
//		System.out.println("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
//		System.out.println("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String property = System.getProperty("user.dir");
//			String filePath = property+"/target/classes/picture/";
        String filePath = property+"/src/main/resources/public/picture/";
        String savePath = filePath+fileName;
        String path ="picture/" + fileName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error();
        }
        return new Result(ResultCode.OK,path);
    }


    @ApiOperation("用户注册")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "userName", value = "用户账号", required = true),
            @ApiImplicitParam(name = "userPassword", value = "密码", required = true),
            @ApiImplicitParam(name = "account", value = "用户姓名", required = true),
            @ApiImplicitParam(name = "types", value = "用户类型", required = true),
            @ApiImplicitParam(name = "sex", value = "用户性别", required = true),
            @ApiImplicitParam(name = "idcard", value = "身份证号", required = true),
            @ApiImplicitParam(name = "phonenumber", value = "电话号码", required = true)
    })
    @RequestMapping(value="/registeruser",method = RequestMethod.POST)
    public Result registerUser(@RequestBody User user) {
        int count = userService.registerCheck(user);
        System.out.println(count);
        if (count == 0) {
            int i = userService.registerUser(user);
            if (i > 0) {
                return new Result(ResultCode.OK);
            }
            return new Result(ResultCode.ERROR);
        }
        return new Result(ResultCode.ERROR1);
    }


    /**
     *获取登录验证码
     */
    @RequestMapping("/captcha.jpg")
    public void getCaptcha() {
        // 设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        // 不缓存此内容
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        try {
            HttpSession session = request.getSession();
            StringBuffer code = new StringBuffer();
            BufferedImage image = captchaUtil.genRandomCodeImage(code);
            session.removeAttribute(KEY_CAPTCHA);
            session.setAttribute(KEY_CAPTCHA, code.toString());
            // 将内存中的图片通过流动形式输出到客户端
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id链表查询了用户的角色
     * @param id
     * @return user
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id) {
        List< Map<String,Object> >user = userService.findUserById(id);

        return new Result(ResultCode.OK,user);
    }



    /**
     * 分页查询全部用户的信息，链表查询了角色信息
     * @return user和role
     */
//    @RequiresRoles("admin")
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public Result findAll( @RequestParam(defaultValue = "1")Integer page,
                           @RequestParam(defaultValue = "10")Integer limit){
        PageInfo<UserVo> pageInfo = userService.findAll(page, limit);
        return new Result(ResultCode.OK,pageInfo.getTotal(),pageInfo.getList());
    }

    /**
     * 用户登录
     *
     * @return
     */
    /*@ApiOperation("用户登录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username", value = "用户账号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public Result login(@RequestParam("username")String username ,@RequestParam("password")String password,String captcha,Boolean remember , HttpSession session) {
        userService.userLogin(username , password ,captcha , remember ,  session);
        return new Result(ResultCode.OK);
    }*/

    @ApiOperation("用户登录")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "username", value = "用户账号", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)
    })
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public Result login(@RequestBody UserLogin userLogin) {
        User user = userService.userLogin(userLogin.getUsername(), userLogin.getPassword(), userLogin.getCaptcha(), userLogin.getRemember(), userLogin.getSession());
        return new Result(ResultCode.OK,user);
    }

//  登出  使用自定义过滤器登出
//    @RequestMapping(value="/user/logout",method = RequestMethod.GET)
//    public RedirectView logout() {
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
//        return new RedirectView("/page/login/login.html");
//    }


    /**
     *  新增用户
     * @param user
     * @return
     */
    @RequiresRoles(value={"admin","administrator"},logical= Logical.OR)
    @RequestMapping(value="/user",method = RequestMethod.POST)
    public Result insertUser(@RequestBody User user) {
        int i = userService.insertUser(user);
        if (i>0){
            return new Result(ResultCode.OK);
        }
        return new Result(ResultCode.ERROR);
    }


    /**
     * 更新用户
     * @param id
     * @param user
     * @return
     */
    @RequiresRoles(value={"admin","administrator"},logical= Logical.OR)
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public Result update(@PathVariable(value = "id")String id,@RequestBody User user) {
        if (user==null){
            throw new MyException(ResultCode.NULLPARM);
        }
        user.setUserId(id);
        int i = userService.saveUser(user);
        if (i>0){
            return Result.ok();
        }
        return Result.error();
    }


    /**
     * 删除单个用户
     * @param id
     * @return
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    public Result deleteById(@PathVariable(value = "id") String id) {
        userService.deleteById(id);
        return Result.ok();
    }


    /**
     * 批量删除用户
     * @param ids ids
     * @return int
     */
    @RequiresRoles(value={"administrator"},logical= Logical.OR)
    @RequestMapping(value="/userByBatchDelete",method = RequestMethod.POST)
    public Result batchDeleteUserByIds(String ids) {
        int i = userService.batchDeleteUserByIds(ids);
        if (i==0){
            return Result.failure();
        }
        return Result.ok();
    }


    /**
     * 给用户分配角色
     * @param map
     * @return
     */
    @RequiresRoles(value={"administrator"},logical= Logical.OR)
    @RequestMapping(value="/user/assignRoles",method = RequestMethod.PUT)
    public Result assignUserRoles(@RequestBody Map map ) {

        String userId = (String) map.get("userId");
        String roles = (String) map.get("roles");
        int i = userService.assignUserRoles(userId,roles);
        if (i>0) {
            return new Result(ResultCode.OK);
        }
        return Result.failure();
    }

    /**
     * 登录首页根据用户名加载 左侧菜单列表
     * 如果用户的角色是admin查取所有权限菜单
     * @return
     */
    @RequestMapping(value="/user/selectIndexMenu",method = RequestMethod.GET)
    public Result selectIndexMenu( ) {
        List< MenuTreeVo > menuTreeList = userService.selectIndexMenu();
        return new Result(ResultCode.OK,menuTreeList);
    }

    /**
     * 从session中获取用户信息 用于提供用户设置密码 个人信息
     * @return
     */
    @RequestMapping(value="/user/nowUserInfo",method = RequestMethod.GET)
    public Result nowUserInfo() {

        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        User user = userService.findUserByName(username);
        return new Result(ResultCode.OK, user);
    }

    /**
     * 从session中获取用户信息 用于提供用户设置密码 个人信息
     * @param id
     * @param oldPassword
     * @param newPassword
     * @param newConfirmPassword
     * @return
     */
    @RequestMapping(value="/user/newPassword/{id}",method = RequestMethod.PUT)
    public Result newPassword(@PathVariable(value = "id")String id,String oldPassword,String newPassword,String newConfirmPassword) {
        if (oldPassword==null|| newPassword ==null || newConfirmPassword ==null){
            throw  new MyException(ResultCode.NULL,"请输入密码！");
        }

        if (!newConfirmPassword.equals(newPassword)){
            throw  new MyException(ResultCode.NULL,"新密码不相同，请确认后提交！");
        }
        int i = userService.setNewPassword(id,oldPassword,newPassword);
        return new Result(ResultCode.OK );
    }


    /**
     * 用户员工头像上传
     * @param file 头像
     */
    @PostMapping("/user/uploadImage/{userId}")
    public Result uploadImage(@PathVariable(value = "userId")String userId,MultipartFile file) {
        String url = userService.uploadImage(userId,file);
        return new Result(ResultCode.OK ,url);
    }


}
